﻿using Assets.Core.Common.Web;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Nucleic.Core;
using Nucleic.Core.DoMain;
using Nucleic.Core.Utils;
using Nucleic.Core.Utils.hebcz;
using YinLong.Tool.Net.HttpHelperMin;

namespace Nucleic.Web.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class InvoiceController : ControllerBase
    {
        private readonly ILogger<InvoiceController> _logger;

        public InvoiceController(ILogger<InvoiceController> logger)
        {
            _logger = logger;

        }
        /// <summary>
        /// 查询发票状态
        /// </summary>
        /// <param name="orders_id"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("QueryStatus")]
        public Result QueryStatus(string orders_id)
        {
            HttpHelperMin http = new HttpHelperMin();
            HttpItemMin httpitem = new HttpItemMin()
            {
                URL = "http://10.10.20.20:7991/search/meinvoicestatus",
                Method = "POST",
                ContentType = "application/json",
                Postdata = JsonConvert.SerializeObject(new MeInvoiceStatus { bizcode = orders_id }),
            };
            var resule = http.GetHtml(httpitem);
            var invStatus = JsonConvert.DeserializeObject<ReturnData<MeInvoiceStatusDto>>(resule.Html);
            _logger.LogInformation(orders_id + "查询发票状态:" + resule.Html);
            return Result.success(resule.Html);
        }
        /// <summary>
        /// 获取发票二维码
        /// </summary>
        /// <param name="orders_id"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Query")]
        public Result Query(string orders_id)
        {
            var order = SqlSugarFactory.Instance.Queryable<order_info>().First(i => i.orders_id == orders_id&&i.status=="0");
            if (order == null)
            {
                return Result.fail("订单异常");
            }
            //查询本地数据库是否已经获取过
            if (string.IsNullOrWhiteSpace(order.einvoicecode) ||
                string.IsNullOrWhiteSpace(order.einvoicenumber) || string.IsNullOrWhiteSpace(order.randomnumber))
            {
                //查询发票状态
                HttpHelperMin http = new HttpHelperMin();
                HttpItemMin httpitem = new HttpItemMin();
                var invStatus = hebczUtil.invoicestatus(orders_id);
                _logger.LogInformation($"获取发票二维码->[{orders_id}]->查询发票状态:" + JsonConvert.SerializeObject(invStatus));
                //如果没有获取过，申请电子发票
                if (invStatus.code < 1 || invStatus.data.Count == 0 || invStatus.data[0].state == "0")
                {
                    _logger.LogInformation($"获取发票二维码->[{orders_id}]->重新申请电子发票" );
                  
                    var item = SqlSugarFactory.Instance.Queryable<check_item>().First(i => i.item_id == order.item_id);
                    var set = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
                    //未成功
                    mkomedicaleinvoiceModel model = new mkomedicaleinvoiceModel()
                    {
                        einvoicespecimen = "1",
                        issuedate = order.pay_time.ToString("yyyyMMdd"),
                        issuetime = order.pay_time.ToString("hh:mm:ss"),
                        payerpartytype = "1",
                        payerpartyname = order.pat_name,
                        totalamount = double.Parse(order.price.ToString()).ToString(),
                        bizcode = orders_id,
                        handlingperson = hebczConst.handlingperson,
                        checker = hebczConst.checker,
                        fundpayamount = "0",
                        otherpayamount = "0",
                        accountpayamount = "0",
                        ownpayamount = double.Parse(order.price.ToString()).ToString(),
                        //relatedinvoicecode = "1253",
                        //relatedinvoicenumber = orders_id,
                    };
                    model.details.Add(new details
                    {
                        itemcode = hebczConst.item_code,
                        itemname = hebczConst.item_name,
                        itemamount = double.Parse(order.price.ToString()).ToString(),

                    });
                    model.auxdetails.Add(new auxdetails
                    {
                        auxitemrelatedcode = hebczConst.item_code,
                        auxitemrelatedname = hebczConst.item_name,
                        auxitemname = item.name,
                        auxitemamount = double.Parse(order.price.ToString()).ToString()
                    });

                    _logger.LogInformation($"获取发票二维码->[{orders_id}]->重新申请电子发票Data:"+ JsonConvert.SerializeObject(model, set));

                    httpitem = new HttpItemMin()
                    {
                        URL = hebczConst.Url + "/mkomedicaleinvoice",
                        Method = "POST",
                        ContentType = "application/json",
                        Postdata = JsonConvert.SerializeObject(model),
                    };
                    var resule = http.GetHtml(httpitem);
                    _logger.LogInformation($"获取发票二维码->[{orders_id}]->重新申请电子发票返回:" + resule.Html);

                    var d = JsonConvert.DeserializeObject<ReturnData<MeInvoiceStatusDto>>(resule.Html);
                    if (d!=null&&d.code == 1)
                    {
                        return Result.fail("发票申请成功,请稍后查看!");
                    }
                    else
                    {
                        return Result.fail("发票申请失败," + d.msg);

                    }

                }
                else
                {
                    order.einvoicecode = invStatus.data[0].einvoicecode;
                    order.einvoicenumber = invStatus.data[0].einvoicenumber;
                    order.randomnumber = invStatus.data[0].randomnumber;
                    order.invoiceStatus = 1;
                    SqlSugarFactory.Instance.Updateable(order).ExecuteCommand();
                    return Result.success(new
                    {
                        qrcode = Core.Utils.QRCodeHelper.BitmapConvertToString(Core.Utils.QRCodeHelper.GenerateQRCode($"http://nontax.hebcz.cn/static/esq?ec={invStatus.data[0].einvoicecode}&en={invStatus.data[0].einvoicenumber}&rn={invStatus.data[0].randomnumber}")),
                        order.einvoicecode,
                        order.einvoicenumber,
                        order.randomnumber
                    });
                }
            }
            else
            {
                return Result.success(new
                {
                    qrcode = Core.Utils.QRCodeHelper.BitmapConvertToString(Core.Utils.QRCodeHelper.GenerateQRCode($"http://nontax.hebcz.cn/static/esq?ec={order.einvoicecode}&en={order.einvoicenumber}&rn={order.randomnumber}")),
                    order.einvoicecode,
                    order.einvoicenumber,
                    order.randomnumber
                });

            }

        }
    }
}
